package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.entity.CartInfo;
import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author lfy
 * @Description
 * @create 2023-07-31 10:39
 */
@RequestMapping("/api/cart")
@RestController
public class CartRestController {


    @Autowired
    CartService cartService;
    /**
     * 返回购物车列表所有商品数据
     * 重要：购物车合并（临时、用户）
     * @return
     */
    @GetMapping("/cartList")
    public Result cartList(){
        //查询购物车列表，直接查询redis中的所有商品返回即可
        String cartKey = cartService.determinCartKey();
        cartService.mergeCart();
        List<CartInfo> infos = cartService.cartList(cartKey);
        return Result.ok(infos);
    }

    /**
     * 添加/减少商品数量
     * @param skuId
     * @param num
     * @return
     */
    @PostMapping("/addToCart/{skuId}/{num}")
    public Result addToCart(@PathVariable("skuId") Long skuId,
                            @PathVariable("num") Integer num){

        String cartKey = cartService.determinCartKey();

        cartService.updateNum(cartKey,skuId,num);
        return Result.ok();
    }

    /**
     * 修改商品选中状态
     * @param skuId
     * @param status
     * @return
     */
    @GetMapping("/checkCart/{skuId}/{status}")
    public Result checkedStatus(@PathVariable("skuId") Long skuId,
                                @PathVariable("status") Integer status){

        cartService.updateStatus(cartService.determinCartKey(),skuId,status);

        return Result.ok();
    }

    /**
     * 删除商品
     * @return
     */
    @DeleteMapping("/deleteCart/{skuId}")
    public Result delete(@PathVariable("skuId") Long skuId){

        cartService.deleteCartInfo(cartService.determinCartKey(),skuId);

        return Result.ok();
    }
}
